package com.xixi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xixi.entity.Favorite;
import com.xixi.entity.ProductImage;
import com.xixi.mapper.FavoriteMapper;
import com.xixi.mapper.ProductImageMapper;
import com.xixi.pojo.dto.FavoriteDTO;
import com.xixi.pojo.vo.FavoriteVO;
import com.xixi.pojo.vo.Result;
import com.xixi.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class FavoriteServiceImpl implements FavoriteService {
    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private ProductImageMapper productImageMapper;
    @Override
    public List<FavoriteVO> listById(Integer id) {
        List<FavoriteVO> list = favoriteMapper.listById(id);
        for (FavoriteVO favoriteVO : list) {
            favoriteVO.setProductImage(getProductImageUrl(favoriteVO.getProductId()).get(0));
        }
        return list;
    }

    @Override
    public Result insert(FavoriteDTO favoriteDTO) {
        Favorite favorite= BeanUtil.toBean(favoriteDTO, Favorite.class);
        favorite.setCreateTime(LocalDateTime.now());
        favorite.setUpdateTime(LocalDateTime.now());
        if(favoriteMapper.insert(favorite)>0){
            return Result.success("收藏成功");
        }else{
            return Result.error("收藏失败");
        }
    }

    @Override
    public Result delete(List<Integer> ids) {
        if(favoriteMapper.deleteBatchIds(ids)>0){
            return Result.success("取消收藏成功");
        }else{
            return Result.error("取消收藏失败");
        }
    }

    public List<String> getProductImageUrl(Integer id) {
        List<ProductImage> images = productImageMapper.selectByProductId(id);
        List<String> imageUrls = new ArrayList<>();
        for (ProductImage image : images) {
            imageUrls.add(image.getImageUrl());
        }
        return imageUrls;
    }
}
